﻿using System;
using System.Reflection;
using System.Globalization;
using Optparse;

namespace Optparse.Tester.Proxy {
    public class CommandParserProxy {
        private object proxyObject;
        private Type proxyobjectType;

        public CommandParserProxy(string cmdline) {
            Type optParser = typeof(OptionParser);

            proxyobjectType = optParser.GetNestedType("CommandParser", BindingFlags.NonPublic);
            if (proxyobjectType == null)
                throw new ApplicationException("The nested class CommandParser is not found.");

            proxyObject = Activator.CreateInstance(proxyobjectType, cmdline);

            if (proxyObject == null)
                throw new ApplicationException("CommandParser object can't be created.");
        }

        public bool EOF {
            get {
                try {
                    object result = proxyobjectType.InvokeMember("EOF", BindingFlags.GetProperty, null, proxyObject, null);
                    return (bool)result;
                } catch (TargetInvocationException tte) {
                    throw tte.InnerException;
                }
            }
        }

        public string NextToken() {
            MethodInfo methodInfo = proxyobjectType.GetMethod("NextToken");
            if (methodInfo == null)
                throw new ApplicationException("The proxy object don't contain NextToken method.");

            try {
                object obj = methodInfo.Invoke(proxyObject, null);
                if (obj != null) {
                    object obj2 = obj.GetType().InvokeMember("Symbol", BindingFlags.GetField, null, obj, null);
                    return (string)obj2;
                }
                throw new ApplicationException("No result");
            } catch (TargetInvocationException ex) {
                throw ex.InnerException;
            }
        }
    }
}
